package com.maiji.cloud.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.maiji.cloud.microservice.UserInfoService;
import com.maiji.cloud.response.shopingmall.*;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.maiji.cloud.config.MyRedisConfig;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.entities.login.Label;
import com.maiji.cloud.entities.shopingmall.DownPriceGoodsLog;
import com.maiji.cloud.entities.shopingmall.DownPriceGoodsManage;
import com.maiji.cloud.entities.shopingmall.DownPriceUserLog;
import com.maiji.cloud.entities.shopingmall.Goods;
import com.maiji.cloud.entities.shopingmall.LabelMiddleGoods;
import com.maiji.cloud.entities.shopingmall.ShopingCart;
import com.maiji.cloud.entities.shopingmall.ShopingOrder;
import com.maiji.cloud.entities.shopingmall.ShopingOrderMiddleShopingCart;
import com.maiji.cloud.mapper.DownPriceLogMapper;
import com.maiji.cloud.mapper.DownPriceManageMapper;
import com.maiji.cloud.mapper.DownPriceUserLogMapper;
import com.maiji.cloud.mapper.GoodsMapper;
import com.maiji.cloud.mapper.LabelMiddleGoodsMapper;
import com.maiji.cloud.mapper.ShopingCartMapper;
import com.maiji.cloud.mapper.ShopingOrderMapper;
import com.maiji.cloud.request.BaseInputDto;
import com.maiji.cloud.request.IdInputDto;
import com.maiji.cloud.request.shopingmall.AddDownPriceUserLogReqDto;
import com.maiji.cloud.request.shopingmall.DownPriceDetailReqDto;
import com.maiji.cloud.request.shopingmall.DownPriceGoodsReqDto;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.response.login.UserInfoResDto;
import com.maiji.cloud.response.shopingmall.DownPriceDetailResDto.DownPriceDetailResData;
import com.maiji.cloud.service.AppLoginFeignService;
import com.maiji.cloud.service.DownPriceGoodsService;
import com.maiji.cloud.service.ShopingOrderMiddleShopingCartService;
import com.maiji.cloud.utils.Arith;
import com.maiji.cloud.utils.CommonIntValueEnum;
import com.maiji.cloud.utils.RedisUtil;
import com.maiji.cloud.utils.TimeUtil;
import com.maiji.cloud.utils.UUID_MD5;

@Service
@Transactional
public class DownPriceGoodsServiceImpl implements DownPriceGoodsService {
	Logger logger = LoggerFactory.getLogger(DownPriceGoodsServiceImpl.class);

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserInfoService userInfoService;
	@Autowired
	private DownPriceManageMapper downPriceManageMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private DownPriceLogMapper downPriceLogMapper;

	@Autowired
	private DownPriceManageMapper downPriceManage;
	@Autowired
	private DownPriceUserLogMapper downPriceUserLogMapper;
	@Autowired
	private AppLoginFeignService appLoginFeignService;
	@Autowired
	private LabelMiddleGoodsMapper labelMiddleGoodsMapper;
	@Autowired
	private ShopingCartMapper shopingCartMapper;
	@Autowired
	private ShopingOrderMapper shopingOrderMapper;
	@Autowired
	private ShopingOrderMiddleShopingCartService somscService;

	@Override
	public DownPriceGoodsListResDto getDownPriceGoodsList(DownPriceGoodsReqDto param) {
		logger.info("DownPriceGoodsServiceImpl.getExchangeLogList,param is {}", JSON.toJSONString(param));
		AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO,
				param.getMaijiToken(), userInfoService);

		Integer start = (param.getPage() - 1) * param.getSize();
		// 获得砍价免费拿商品列表
		List<DownPriceGoodsManage> list = downPriceManageMapper.selectListByTime(new Date(), start, param.getSize());

		// 返回列表
		List<DownPriceGoodsListResData> listDownPriceGoodsListResData = new ArrayList<DownPriceGoodsListResData>();

		for (DownPriceGoodsManage downPriceGoodsManage : list) {
			DownPriceGoodsListResData downPriceGoodsListResData = new DownPriceGoodsListResData();

			GoodsResData goods = goodsMapper.findGoodsById(downPriceGoodsManage.getGoodId());
			BeanUtils.copyProperties(goods, downPriceGoodsListResData);

			DownPriceGoodsLog downPriceGoodsLog = downPriceLogMapper.selectOneByDownPriceManageId(appUser.getUuId(),
					downPriceGoodsManage.getUuId());
			// 该用户是否对该商品进行砍价
			if (downPriceGoodsLog == null || new Date().getTime() > downPriceGoodsLog.getEndTime().getTime()) {
				downPriceGoodsListResData.setIsNo(0);
			} else {
				downPriceGoodsListResData.setIsNo(1);
				downPriceGoodsListResData.setDownPriceGoodsLogId(downPriceGoodsLog.getUuId());
			}

			downPriceGoodsListResData.setGoodsId(downPriceGoodsManage.getGoodId());
			downPriceGoodsListResData.setStartPrice(downPriceGoodsManage.getStartPrice());

			listDownPriceGoodsListResData.add(downPriceGoodsListResData);
		}
		DownPriceGoodsListResDto downPriceGoodsListResDto = new DownPriceGoodsListResDto(Status.SUCCESS);
		downPriceGoodsListResDto.setData(listDownPriceGoodsListResData);

		return downPriceGoodsListResDto;
	}

	@Override
	public DownPriceDetailResDto getDownPriceDetail(DownPriceDetailReqDto param) {
		logger.info("DownPriceGoodsServiceImpl.getDownPriceDetail,param is {}", JSON.toJSONString(param));

		AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO,
				param.getData().getMaijiToken(), userInfoService);

		String userId = null;
		if (appUser != null) {
			userId = appUser.getUuId();
		}

		Date nowTime = new Date();
		DownPriceGoodsManage downPriceGoodsManage = downPriceManage.selectOneByGoodId(param.getData().getGoodId(),
				nowTime);
		GoodsResData goods = goodsMapper.findGoodsById(downPriceGoodsManage.getGoodId());

		DownPriceDetailResDto downPriceDetailResDto = new DownPriceDetailResDto(Status.SUCCESS);
		DownPriceDetailResData downPriceDetailResData = downPriceDetailResDto.dataInstance();

		BeanUtils.copyProperties(downPriceGoodsManage, downPriceDetailResData);
		downPriceDetailResData.setMainImage(goods.getMainImage());
		downPriceDetailResData.setName(goods.getName());
		downPriceDetailResData.setGoodId(downPriceGoodsManage.getGoodId());

		DownPriceGoodsLog downPriceGoodsLog = null;
		if (StringUtils.isNotBlank(param.getData().getDownPriceGoodsLogId())) {
			downPriceGoodsLog = downPriceLogMapper.selectById(param.getData().getDownPriceGoodsLogId());
		}

		if (downPriceGoodsLog != null) {
			Double sumPrice = downPriceUserLogMapper.getSumByUserLogId(downPriceGoodsLog.getUuId());
			downPriceDetailResData.setDownPriceSum(sumPrice);
			downPriceDetailResData.setDownPriceGoodsLogId(downPriceGoodsLog.getUuId());
			downPriceDetailResData.setStatus(downPriceGoodsLog.getStatus());
			downPriceDetailResData.setEndTime(downPriceGoodsLog.getEndTime());
			userId = downPriceGoodsLog.getUserId();
		} else {
			downPriceDetailResData.setDownPriceSum(0.0);
		}

		// 获取商品所在阶段的标签id
		EntityWrapper<LabelMiddleGoods> wrapper = new EntityWrapper<LabelMiddleGoods>();
		wrapper.eq("goods_id", param.getData().getGoodId());
		List<LabelMiddleGoods> listLabelMiddleGoods = labelMiddleGoodsMapper.selectList(wrapper);

		List<String> labelIds = listLabelMiddleGoods.stream()
				.map(listLabelMiddleGood -> listLabelMiddleGood.getLabelId()).collect(Collectors.toList());

		BaseInputDto<String> inputDto = new BaseInputDto<String>();
		String labelIdsString = String.join(",", labelIds);
		inputDto.setData(labelIdsString);
		List<Label> labelsData = appLoginFeignService.getLabelsByIds(inputDto);

		List<String> labelName = labelsData.stream().map(label -> label.getName()).collect(Collectors.toList());
		downPriceDetailResData.setStageLabels(labelName);

		 BaseInputDto<IdInputDto> userInfoParam = new  BaseInputDto<IdInputDto>();
		 IdInputDto idInputDto = new IdInputDto();
		 idInputDto.setId(userId);
		 userInfoParam.setData(idInputDto);
		// 获取用户信息
		UserInfoResDto userInfoResDto = appLoginFeignService.getUserInfoWithUserId(userInfoParam);
		if(userInfoResDto != null) {
			downPriceDetailResData.setHeadUrl(userInfoResDto.getData().getHeadUrl());
			downPriceDetailResData.setNickName(userInfoResDto.getData().getNickName());
		}
		
		downPriceDetailResDto.setData(downPriceDetailResData);
		

		return downPriceDetailResDto;
	}

	@Override
	public DownPriceUserLogListResDto getDownPriceUserLogList(DownPriceDetailReqDto param) {
		logger.info("DownPriceGoodsServiceImpl.getDownPriceUserLogList,param is {}", JSON.toJSONString(param));
		DownPriceGoodsLog downPriceGoodsLog = downPriceLogMapper.selectById(param.getData().getDownPriceGoodsLogId());
		List<DownPriceUserLog> list = new ArrayList<DownPriceUserLog>();
		if (downPriceGoodsLog != null) {
			list = downPriceUserLogMapper.getListByUserLogId(downPriceGoodsLog.getUuId());
		}
		for(DownPriceUserLog downPriceUserLog : list) {
			if(StringUtils.isBlank(downPriceUserLog.getNikename()) || StringUtils.isBlank(downPriceUserLog.getHeadUrl())) {
				BaseInputDto<IdInputDto> baseInputDto = new BaseInputDto<IdInputDto> ();
				IdInputDto idInputDto = new IdInputDto();
				idInputDto.setId(downPriceUserLog.getOpenId());
				baseInputDto.setData(idInputDto);
				UserInfoResDto userInfoResDto = appLoginFeignService.getUserInfoWithUserId(baseInputDto);
				downPriceUserLog.setHeadUrl(userInfoResDto.getData().getHeadUrl());
				downPriceUserLog.setNikename(userInfoResDto.getData().getNickName());
			}
		}
		

		DownPriceUserLogListResDto downPriceUserLogListResDto = new DownPriceUserLogListResDto(Status.SUCCESS);
		downPriceUserLogListResDto.setData(list);
		return downPriceUserLogListResDto;
	}

	@Override
	public BaseResDto addDownPriceUserLog(AddDownPriceUserLogReqDto param) {
		logger.info("DownPriceGoodsServiceImpl.addDownPriceUserLog,param is {}", JSON.toJSONString(param));

		AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO,
				param.getData().getMaijiToken(), userInfoService);
		if (appUser == null) {
			return new BaseResDto(Status.PARAMETERERROR, "参数错误");
		}
		BaseInputDto<IdInputDto> inputDto = new BaseInputDto<IdInputDto>();
		IdInputDto idInputDto = new IdInputDto();
		idInputDto.setId(appUser.getUuId());
		inputDto.setData(idInputDto);
		// 获取用户信息

		UserInfoResDto userInfoResDto = appLoginFeignService.getUserInfoWithUserId(inputDto);

		Date nowTime = new Date();
		DownPriceGoodsManage downPriceGoodsManage = downPriceManage.selectOneByGoodId(param.getData().getGoodId(),
				nowTime);

		if (StringUtils.isEmpty(param.getData().getShopingAddressId())
				&& StringUtils.isEmpty(param.getData().getDownPriceGoodsLogId())) {
			return new BaseResDto(Status.PARAMETERERROR, "请选择收货地址");
		}

		Date startTime = downPriceGoodsManage.getStartTime();
		if (downPriceGoodsManage.getNum() != null) {
			startTime = TimeUtil.getDateTime(new Date(), downPriceGoodsManage.getNum(), 1);
		}

		// 查看是否帮别人砍过价格
		DownPriceUserLog downPriceUserLog = downPriceUserLogMapper.selectOneByOpenId(appUser.getUuId(), startTime,
				new Date());
		if (downPriceUserLog != null && !StringUtils.isEmpty(param.getData().getDownPriceGoodsLogId())) {
			return BaseResDto.baseResDto(Status.ERROR, "砍价失败，已经帮别人砍过价格");
		}

		DownPriceGoodsLog downPriceGoodsLog = null;
		if (StringUtils.isEmpty(param.getData().getDownPriceGoodsLogId())) {
			downPriceGoodsLog = new DownPriceGoodsLog();
			downPriceGoodsLog.setUuId(UUID_MD5.getUUID());
			downPriceGoodsLog.setUserId(appUser.getUuId());
			downPriceGoodsLog.setDownPriceManageId(downPriceGoodsManage.getUuId());
			downPriceGoodsLog.setInTime(new Date());
			downPriceGoodsLog.setEndTime(TimeUtil.getDateTime(new Date(), downPriceGoodsManage.getNum(), 0));
			downPriceGoodsLog.setShopingAddressId(param.getData().getShopingAddressId());
			downPriceLogMapper.insert(downPriceGoodsLog);
		}
		
		

		downPriceUserLog = new DownPriceUserLog();

		BeanUtils.copyProperties(param.getData(), downPriceUserLog);
		downPriceUserLog.setUuId(UUID_MD5.getUUID());
		downPriceUserLog.setHeadUrl(userInfoResDto.getData().getHeadUrl());
		downPriceUserLog.setNikename(userInfoResDto.getData().getNickName());
		downPriceUserLog.setOpenId(appUser.getUuId());
		if (!StringUtils.isEmpty(param.getData().getDownPriceGoodsLogId())) {
			DownPriceGoodsLog newDownPriceGoodsLog = downPriceLogMapper.selectById(param.getData().getDownPriceGoodsLogId());
			if(newDownPriceGoodsLog.getEndTime().getTime() < new Date().getTime()) {
				return new BaseResDto(Status.PARAMETERERROR,"活动已经结束");
			}
			
			downPriceUserLog.setDownPriceGoodsLogId(param.getData().getDownPriceGoodsLogId());
			downPriceUserLog.setType(CommonIntValueEnum.DOWN_PRICE_USER_LOG_OTHER.getValue());
		} else {
			downPriceUserLog.setDownPriceGoodsLogId(downPriceGoodsLog.getUuId());
			downPriceUserLog.setType(CommonIntValueEnum.DOWN_PRICE_USER_LOG_ONESELF.getValue());
		}

		// 判断是否在平台砍过价格，砍过就是老用户，否则就是新用户
		List<DownPriceUserLog> listDownPriceUserLog = downPriceUserLogMapper.getListByUserId(appUser.getUuId());

		Double price = Arith.getRandomNum(downPriceGoodsManage.getNewUserMin(), downPriceGoodsManage.getNewUserMax());
		// 老用户
		if (listDownPriceUserLog.size() > 0) {
			price = Arith.getRandomNum(downPriceGoodsManage.getMin(), downPriceGoodsManage.getMax());
		}

		// 砍掉的总金额
		Double sumPrice = 0.0;
		if (!StringUtils.isEmpty(param.getData().getDownPriceGoodsLogId())) {
			sumPrice = downPriceUserLogMapper.getSumByUserLogId(param.getData().getDownPriceGoodsLogId());
		}

		// 余额
		Double balance = Arith.subtract(2, downPriceGoodsManage.getStartPrice(), sumPrice);
		if (downPriceGoodsManage.getStartPrice() <= sumPrice)
			return new BaseResDto(Status.PARAMETERERROR, "该商品已砍价格成功");
		downPriceUserLog.setPrice(price);
		downPriceUserLog.setInTime(new Date());
		downPriceUserLogMapper.insert(downPriceUserLog);

		// 已经砍成功
		if (Arith.add(2, sumPrice, price) >= downPriceGoodsManage.getStartPrice()) {
			logger.info("砍价的商品{}已砍成功", param.getData().getDownPriceGoodsLogId());
			downPriceGoodsLog = downPriceLogMapper.selectById(param.getData().getDownPriceGoodsLogId());
			String orderId = orderInfo(param.getData().getGoodId(), downPriceGoodsLog.getUserId(),
					downPriceGoodsLog.getShopingAddressId());
			// 修改砍价商品记录表
			downPriceGoodsLog.setStatus(CommonIntValueEnum.DOWN_PRICE_GOODS_LOG_STATUS_FINISH.getValue());
			downPriceGoodsLog.setOrderId(orderId);
			downPriceLogMapper.updateById(downPriceGoodsLog);
		}
		return new BaseResDto(Status.SUCCESS);
	}

	/**
	 * 砍价成功后自动生成订单信息
	 * 
	 * @return
	 */
	public String orderInfo(String goodsId, String userId, String shopingAddressId) {
		// 根据商品id获取商品信息
		Goods goods = goodsMapper.selectById(goodsId);

		// 商品加入购物车
		ShopingCart shopingCart = new ShopingCart();
		shopingCart.setUuId(UUID_MD5.getUUID()).setGoodsId(goodsId).setPurchaseQuantity(1)// 购买数量
				.setOriginalPayable(goods.getOriginalPrice()).setPresentPayable(goods.getPresentPrice())
				.setWeightTotal(goods.getWeight()).setDealDate(new Date()).setAddDate(new Date())
				.setUpdateDate(new Date()).setChosen(false)
				.setStatus(CommonIntValueEnum.SHOPPING_CART_STATUS_ALLREADY_PAY.getValue()).setAddAuto(true)
				.setUserId(userId);
		shopingCartMapper.insert(shopingCart);

		// 生成订单信息
		ShopingOrder order = new ShopingOrder();
		order.setUuId(UUID_MD5.getUUID()).setUserId(userId).setOrderNo(UUID_MD5.orderNo()).setDelivery("申通快递")
				.setDeliveryFee(0.0).setWeightTotal(goods.getWeight()).setAmount(0.0).setPayType(0)// 砍价免费拿
				.setCreateDate(new Date()).setShopingAddressId(shopingAddressId)
				.setStatus(CommonIntValueEnum.SHOPPING_ORDER_STATUS_STAY_SHIPMENTS.getValue());
		shopingOrderMapper.insert(order);

		// 保存购物车和订单中间表

		ShopingOrderMiddleShopingCart orderMiddleShopingCart = new ShopingOrderMiddleShopingCart()
				.setUuId(UUID_MD5.getUUID()).setShopingCartId(shopingCart.getUuId()).setOrderId(order.getUuId());
		somscService.insert(orderMiddleShopingCart);

		return order.getUuId();
	}

	@Override
	public BaseDataResDto<List<UnderwayDownPriceGoodsData>> userUnderwayDownPriceGoods(String maijiToken) {
		logger.info("DownPriceGoodsServiceImpl.userUnderwayDownPriceGoods,maijiToken is {}", maijiToken);
		AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
		if (appUser == null) {
			return new BaseDataResDto<List<UnderwayDownPriceGoodsData>>(Status.PARAMETERERROR, "token无效");
		}

		List<Map<String, Object>> list = downPriceLogMapper.downPriceLogByUser(appUser.getUuId(), new Date());
		List<UnderwayDownPriceGoodsData> listUnderwayDownPriceGoodsData = new ArrayList<>();
		// 根据商品id获取商品信息
		for (Map<String, Object> map : list) {
			UnderwayDownPriceGoodsData underwayDownPriceGoodsData = new UnderwayDownPriceGoodsData();
			GoodsResData goodsResData = goodsMapper.findGoodsById((String) map.get("goodsId"));
			underwayDownPriceGoodsData.setGoodsId((String) map.get("goodsId"));
			underwayDownPriceGoodsData.setStartPrice((Double) map.get("startPrice"));
			underwayDownPriceGoodsData.setMainImage(goodsResData.getMainImage());
			underwayDownPriceGoodsData.setName(goodsResData.getName());
			underwayDownPriceGoodsData.setDownPriceGoodsLogId((String) map.get("downPriceGoodsLogId"));
			underwayDownPriceGoodsData.setEndTime((Date) map.get("endTime"));
			DownPriceGoodsLog downPriceGoodsLog = downPriceLogMapper
					.selectOneById((String) map.get("downPriceGoodsManageId"), appUser.getUuId());

			if (downPriceGoodsLog != null) {
				Double sumPrice = downPriceUserLogMapper.getSumByUserLogId((String) map.get("downPriceGoodsLogId"));
				underwayDownPriceGoodsData.setDownPriceSum(sumPrice);
				underwayDownPriceGoodsData.setDownPriceGoodsLogId((String) map.get("downPriceGoodsLogId"));
			}

			// 获取商品所在阶段的标签id
			EntityWrapper<LabelMiddleGoods> wrapper = new EntityWrapper<LabelMiddleGoods>();
			wrapper.eq("goods_id", (String) map.get("goodsId"));
			List<LabelMiddleGoods> listLabelMiddleGoods = labelMiddleGoodsMapper.selectList(wrapper);

			List<String> labelIds = listLabelMiddleGoods.stream()
					.map(listLabelMiddleGood -> listLabelMiddleGood.getLabelId()).collect(Collectors.toList());

			BaseInputDto<String> inputDto = new BaseInputDto<String>();
			String labelIdsString = String.join(",", labelIds);
			inputDto.setData(labelIdsString);
			List<Label> labelsData = appLoginFeignService.getLabelsByIds(inputDto);

			List<String> labelName = labelsData.stream().map(label -> label.getName()).collect(Collectors.toList());
			underwayDownPriceGoodsData.setStageLabels(labelName);

			listUnderwayDownPriceGoodsData.add(underwayDownPriceGoodsData);
		}

		BaseDataResDto<List<UnderwayDownPriceGoodsData>> baseDataResDto = new BaseDataResDto<List<UnderwayDownPriceGoodsData>>(
				Status.SUCCESS);
		baseDataResDto.setData(listUnderwayDownPriceGoodsData);

		return baseDataResDto;
	}

	@Override
	public BaseResDto endDownPriceGoods(DownPriceDetailReqDto param) {
		logger.info("DownPriceGoodsServiceImpl.endDownPriceGoods,param is {}", JSON.toJSONString(param));
		if(StringUtils.isBlank(param.getData().getDownPriceGoodsLogId())) return new BaseResDto(Status.PARAMETERERROR,"砍价记录id为空");
		DownPriceGoodsLog downPriceGoodsLog = downPriceLogMapper.selectById(param.getData().getDownPriceGoodsLogId());
		if(downPriceGoodsLog == null)return new BaseResDto(Status.PARAMETERERROR);
		downPriceGoodsLog.setEndTime(new Date());
		downPriceGoodsLog.setStatus(CommonIntValueEnum.DOWN_PRICE_GOODS_LOG_STATUS_END.getValue());
		downPriceLogMapper.updateById(downPriceGoodsLog);
		
	    return new BaseResDto(Status.SUCCESS);
	}

}
